package cn.cena.exception;

import cn.cena.util.AjaxResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.BufferedReader;
import java.util.List;

/**
 * 全局异常处理
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = GlobalException.class)
    public AjaxResult globalExceptionHandler(GlobalException e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public AjaxResult MethodArgumentNotValidException(MethodArgumentNotValidException e){
        e.printStackTrace();
        // 拿到错误信息
        List<ObjectError> errors = e.getBindingResult().getAllErrors();

        StringBuilder s = new StringBuilder();
        errors.forEach(error->{
            s.append(error.getDefaultMessage()).append(";");
        });
        return AjaxResult.me().setSuccess(false).setMessage(s.toString());
    }

    @ExceptionHandler(value = Exception.class)
    public AjaxResult exceptionHandler(Exception e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage("系统异常，正在殴打程序员");
    }
}
